#include "Dialog.h"

#include "_Global/GlobalClass.h"

#include <QApplication>
#include <QDebug>
#include <QResource>
#include <QDir>
//#include <QMessageBox>

#include <QThread>
#include <QSqlDatabase>
#include <QLibrary>



int main(int argc, char *argv[])
{
    QApplication app(argc, argv);



    qDebug()<<"[Updater]Main ThreadId:"<<QThread::currentThreadId();

    qDebug() << "[Updater]Path:" << QDir::currentPath() << app.applicationDirPath()
             << QDir::homePath() << QDir::rootPath() << QDir::tempPath();


#if defined(Q_OS_MACOS)
    //苹果默认工作目录是 ~(/Users/[User])，所以需要更改默认路径程序当前路径，否则相对目录无法使用
    //安卓的默认工作目录是/data/data/appName/files，但应用路径在/data/app/appName/lib下
    //win下是相同的
    QDir::setCurrent(QCoreApplication::applicationDirPath());
#endif

    //所有窗口关闭后不退出程序，否则加载的lib也会自动退出。
    QGuiApplication::setQuitOnLastWindowClosed(false);



    QCoreApplication::addLibraryPath(QDir::currentPath());

    /*qDebug() << "-----------libLoad-----------";
    QLibrary lib1("./libqml_QtQuick_Particles.2_particlesplugin_armeabi-v7a.so");
    qDebug() << lib1.load();
    QLibrary lib2("../libs/libqml_QtQuick_Particles.2_particlesplugin_armeabi-v7a.so");
    qDebug() << lib2.load();*/

    qDebug() << "[Updater]sqldrivers:" << QSqlDatabase::drivers();



#if defined(Q_OS_ANDROID)   //android
    copyFileAndSetPermissions("Updater.cfg", QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner);
    copyFileAndSetPermissions("UpdaterConfig.json", QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner);
#endif

    bool ret = QResource::registerResource("Updater.cfg");
    if(!ret)
    {
        //QMessageBox::information(nullptr,"打开失败","载入res文件失败!");
        qWarning()<<"[!WARNING]载入Updater.cfg文件失败!";
        //QMessageBox::information(nullptr,"err load","err");
        //return -2;
    }


    QObject::connect(&app, &QGuiApplication::lastWindowClosed, [=](){
        qDebug() << "[Updater]lastWindowClosed" << QGuiApplication::quitOnLastWindowClosed();
    });


    Dialog w(argc, argv);



/*
    QFile file("UpdateInfo.json");
    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "read json file failed";
        //return;
    }
    else
        qDebug() << "read json yeah";
    QByteArray ba = file.readAll();
    file.close();

    if(!file.open(QIODevice::WriteOnly))
    {
        qDebug() << "read json file failed2";
        //return;
    }
    else
        qDebug() << "read json yeah2";
    file.close();
    */



    //程序退出时调用
    QObject::connect(&app, &QCoreApplication::aboutToQuit, [=]()
    {
        qDebug() << "[Updater]aboutToQuit";
        qDebug() << "[Updater]quitOnLastWindowClosed" << QGuiApplication::quitOnLastWindowClosed();
        //if(g_CommonData.m_pMessageHandlerInfo != nullptr)
        //    delete g_CommonData.m_pMessageHandlerInfo;
    });


    return app.exec();
}
